package com.guoxin.mashibing;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SynchronizationContainer2<T> {

    private static final int MAX = 10;
    private int count = 0;
    private final LinkedList<T> container = new LinkedList<>();
    private Lock lock = new ReentrantLock();
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();


    public void put(T t) {
        try {
            lock.lock();
            while (container.size() >= MAX) {
                producer.await();
            }
            container.add(t);
            count++;
            consumer.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public T get() {
        T t = null;
        try {
            lock.lock();
            while (container.size() == 0) {
                consumer.await();
            }
            t = container.removeFirst();
            count--;
            producer.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return t;
    }

    public static void main(String[] args) throws InterruptedException {
        SynchronizationContainer2<String> sc = new SynchronizationContainer2<>();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {
                    System.out.println(sc.get());
                }
            }, "C" + i).start();
        }

        Thread.sleep(2000);

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 25; j++) {
                    sc.put(Thread.currentThread().getName() + "--" + j);
                }
            }, "P" + i).start();
        }

    }
}
